#include <stdio.h>
#include <time.h>
#include <errno.h>
#include <string.h>
#include <assert.h>

#include "play_avi.h"
#include "debug/debug.h"

static struct play_avi play_avi = {
    .avi.avi_reader = NULL,
};

void ffmpeg_demuxing_init_param(struct media_demuxing_param* param);

int play_count = 0;

void media_play_close(void)
{
    if (play_avi.video_demux != NULL)
    {
        demuxing_close(play_avi.video_demux);
        play_avi.video_demux = NULL;
    }
}

struct media_demuxing * media_play_open(const char* dir, const char* name)
{
    int ret = -1;
    char file_name[MAX_RECORD_FILE_NAME_LENGHT] = { 0 };
    uint64_t duration = 0;
    unsigned int totalTime = 0;
    int min = 0;
    int sec = 0;

	sprintf(file_name, "%s/%s", dir, name);
    play_avi.demuxing_param.input_file = file_name;
    ffmpeg_demuxing_init_param(&play_avi.demuxing_param);

    play_avi.video_demux = demuxing_open(&play_avi.demuxing_param);
    if (play_avi.video_demux == NULL)
    {
        print_error("open demuxing failed.");
        return NULL;
    }
	play_count = 0;

    return play_avi.video_demux;

}

struct media_packet* media_play_read_pkt(void)
{
    struct media_packet* media_pkt = NULL;
    int ret = -1;

    assert(play_avi.video_demux);

    while (true)
    {
        ret = demuxing_one_pkt(play_avi.video_demux, &media_pkt);
        if (ret == -MEDIA_EOF)
        {
            print_debug("arrived to video eof.");
            media_pkt = NULL;
            break;
        }
        if (media_pkt->type != VIDEO_pkt_h264) {
            media_packet_put(media_pkt);
            continue;
        }     

		if(play_count == 1)
		{
			FILE *fp = fopen("thumbial.jpg", "wb+");
			fwrite(media_pkt->data, media_pkt->size, 1, fp);
			fclose(fp);
		}

        break;
    }

    return media_pkt;
}


